package com.zzh.netty.bio;/**
 * @ClassName SocketClient
 * @date 2021/1/28 21:15
 * @Version 1.0
 * @Description //TODO
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *@ClassName SocketClient
 *@date 2021/1/28 21:15
 *@Version 1.0
 *@Description //
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(9000);
        while (true) {
            //在此处会阻塞
            Socket clientSocket = serverSocket.accept();
            System.out.println("有客户端连接了....");
//            handler(clientSocket);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //处理的逻辑
                        handler(clientSocket);
                    }catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            }).start();
        }
    }

    private static void handler(Socket clientSocket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备读取。。。");
        int read = clientSocket.getInputStream().read(bytes);
        System.out.println("read完毕...");
        if (read != -1) {
            System.out.println("接收到客户端数据："+ new String(bytes,0,read));
        }
        clientSocket.getOutputStream().write("HelloClient".getBytes());
        clientSocket.getOutputStream().flush();
    }
}
